package org.example.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.Command.CommonMessage;
import org.example.Command.FileMessage;
import org.example.Command.SendMessage;
import org.example.Utils.StringUtils;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class SendCommandClientHandler extends SimpleChannelInboundHandler<SendMessage> implements SendFile {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SendMessage msg) throws Exception {
        try {
            Integer SequenceId = msg.getSequenceId();
            Path path = Paths.get(msg.getArgs().get("-f"));
            if (path.toFile().isFile()) {
                System.out.println("发送文件");
                SendFile.sendFile(ctx, path.toFile(), null, SequenceId);
            } else if (path.toFile().isDirectory()) {
                int rootCount = path.getNameCount();
                System.out.println("发送文件夹");
                //发送
                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        //创建目录
                        int dirCount = dir.getNameCount();
                        if (dir.compareTo(path) != 0) {
                            Path subPath = dir.subpath(rootCount, dirCount);
                            //目录创建
                            FileMessage filePath = new FileMessage();
                            filePath.setFilePath(subPath.toFile());
                            ctx.writeAndFlush(filePath);
                        }

                        return super.preVisitDirectory(dir, attrs);
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                            throws IOException {
                        //发送文件
                        System.out.println(file.subpath(rootCount, file.getNameCount()));
                        int fileCount = file.getNameCount();
                        Path subPath = file.subpath(rootCount, fileCount);
                        SendFile.sendFile(ctx, file.toFile(), subPath.toFile(), SequenceId);
                        return super.visitFile(file, attrs);
                    }
                });
            }
            //发送完毕信息
            CommonMessage commonMessage = new CommonMessage("FileName:" + StringUtils.getFileName(msg.getArgs().get("-f")));
            commonMessage.setSequenceId(SequenceId);
            commonMessage.setArgs(msg.getArgs());
            ctx.writeAndFlush(commonMessage);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
